package com.ruoyi.common.utils.insensitive;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;

import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.ruoyi.common.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Objects;

/**
 * author:andy
 * 自定义序列化器
 */
@NoArgsConstructor
@AllArgsConstructor
public class PrivacySerializer extends JsonSerializer<String> implements ContextualSerializer {

    private PrivacyTypeEnum privacyTypeEnum;

    private Integer prefixNoMaskLen;

    private Integer suffixNoMaskLen;

    private String symbol;

    @Override
    public void serialize(String origin, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (StringUtils.isNotBlank(origin)&&null!=privacyTypeEnum){
            switch (privacyTypeEnum){
                case ID_CARD:
                    jsonGenerator.writeString(PrivacyUtil.hideIdCard(origin));
                    break;
                case NAME:
                    jsonGenerator.writeString(PrivacyUtil.hideName(origin));
                    break;
                case PHONE:
                    jsonGenerator.writeString(PrivacyUtil.hidePhone(origin));
                    break;
                case EMAIL:
                    jsonGenerator.writeString(PrivacyUtil.hideEmail(origin));
                    break;
                default:
                    throw new IllegalArgumentException("unknown privacy type enum"+privacyTypeEnum);
            }
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty!=null){
            if (Objects.equals(beanProperty.getType().getRawClass(),String.class)){
                PrivacyEncrypt privacyEncrypt=beanProperty.getAnnotation(PrivacyEncrypt.class);
                if (privacyEncrypt==null){
                    privacyEncrypt=beanProperty.getContextAnnotation(PrivacyEncrypt.class);
                }
                if (privacyEncrypt!=null){
                    return new PrivacySerializer(privacyEncrypt.type(),privacyEncrypt.suffixNoMaskLen(),
                            privacyEncrypt.prefixNoMaskLen(), privacyEncrypt.symbol());
                }
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(),beanProperty);
        }

        return serializerProvider.findNullValueSerializer(null);
    }
}
